package com.blockmeta.bbs.immodule.activity;

import android.content.Context;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.SparseBooleanArray;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.blockmeta.bbs.baselibrary.utils.LoadPicUtil;
import com.blockmeta.bbs.baselibrary.utils.ToastUtil;
import com.blockmeta.bbs.businesslibrary.baselist.NewBaseListActivity;
import com.blockmeta.bbs.businesslibrary.widget.CircleImageView;
import com.blockmeta.bbs.immodule.Constants;
import com.blockmeta.bbs.immodule.R;
import com.blockmeta.bbs.immodule.bean.LibraryBookBean;
import com.blockmeta.bbs.immodule.modelimpl.MyLibraryBookModellImpl;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;

import java.util.ArrayList;
import java.util.List;

public class MyLibraryBookSendActivity extends NewBaseListActivity<LibraryBookBean.ResultBean.DataBean, LibraryBookBean, MyLibraryBookModellImpl> {
    private boolean editable = false;
    private boolean chooseSingle = false;
    private SparseBooleanArray mSelectedPositions = new SparseBooleanArray();
    private int mSelectedPos = -1;
    private MyLibraryBookModellImpl mListModel;

    EditText etSearch;
    LinearLayout mSearchKeyWord;
    TextView mTvSearchKeyWord;
    ImageView mIvTextClear;


    @Override
    protected void fillData(BaseViewHolder helper, final LibraryBookBean.ResultBean.DataBean item) {

        ToggleButton toggleButton = helper.getView(R.id.tg_edit_selector);
        toggleButton.setVisibility(editable ? View.VISIBLE : View.GONE);
        toggleButton.setTag(helper.getAdapterPosition());
        toggleButton.setOnCheckedChangeListener(null);
        toggleButton.setChecked(isItemChecked(helper.getAdapterPosition()));
        toggleButton.setOnCheckedChangeListener(mCheckedListener);
        toggleButton.setClickable(false);
        toggleButton.setLongClickable(false);


        ImageView img = helper.getView(R.id.lib_img);
        LoadPicUtil.loadWithPicasso(img, item.getCoverImg());

        CircleImageView avatar = helper.getView(R.id.civ_author);
        LoadPicUtil.loadWithPicasso(avatar, item.getAvatar());
        helper.setText(R.id.tv_title, item.getTitle());
        helper.setText(R.id.tv_author, item.getUsername());
        helper.setText(R.id.tv_date, item.getUploaddate());
        List<String> keys = item.getKey();
        if (keys != null ) {
            int size = keys.size();
            helper.setText(R.id.tv_band1, size > 0 ? keys.get(0) : "");
            helper.setGone(R.id.tv_band1, size > 0 ? true : false);
            helper.setText(R.id.tv_band2, size > 1 ? keys.get(1) : "");
            helper.setGone(R.id.tv_band2, size > 1 ? true : false);
            helper.setText(R.id.tv_band3, size > 2 ? keys.get(2) : "");
            helper.setGone(R.id.tv_band3, size > 2 ? true : false);
            helper.setText(R.id.tv_band4, size > 3 ? keys.get(3) : "");
            helper.setGone(R.id.tv_band4, size > 3 ? true : false);
        }

        helper.setText(R.id.tv_readtime, item.getViewcount() + "次阅读");
        helper.setText(R.id.tv_downloadtime, item.getDowncount() + "次下载");

    }

    private CheckedListener mCheckedListener = new CheckedListener();

    class CheckedListener implements CompoundButton.OnCheckedChangeListener {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

            if (chooseSingle) {
                int position = (int) buttonView.getTag();
                if (mSelectedPos == position) {
                    setItemChecked(position, false);
                    mSelectedPos = -1;
                } else if (mSelectedPos != position && mSelectedPos != -1) {
                    //先取消上个item的勾选状态
                    setItemChecked(mSelectedPos, false);
                    mAdapter.notifyItemChanged(mSelectedPos);
                    //设置新Item的勾选状态
                    mSelectedPos = position;
                    setItemChecked(mSelectedPos, true);
                    mAdapter.notifyItemChanged(position);
                } else if (mSelectedPos == -1) {
                    mSelectedPos = position;
                    setItemChecked(mSelectedPos, true);
                    mAdapter.notifyItemChanged(position);
                }
            } else {
                int position = (int) buttonView.getTag();
                setItemChecked(position, isChecked);
            }
        }
    }

    public void setEditable(boolean editable, boolean chooseSingle) {
        this.editable = editable;
        this.chooseSingle = chooseSingle;
        mSelectedPos = -1;
    }

    public List<LibraryBookBean.ResultBean.DataBean> getCheckedItems() {
        ArrayList<LibraryBookBean.ResultBean.DataBean> selectList = new ArrayList<>();
        int size = mSelectedPositions.size();
        for (int i = 0; i < size; i++) {
            if (mSelectedPositions.valueAt(i)) {
                selectList.add(mAdapter.getItem(mSelectedPositions.keyAt(i)));
            }
        }
        return selectList;
    }

    public int getSelectedPos() {
        return mSelectedPos;
    }


    //设置给定位置条目的选择状态
    private void setItemChecked(int position, boolean isChecked) {
        mSelectedPositions.put(position, isChecked);
    }

    //根据位置判断条目是否选中
    private boolean isItemChecked(int position) {
        return mSelectedPositions.get(position);
    }


    @Override
    protected int getItemLayout() {
        return R.layout.item_librarybook;
    }

    @Override
    protected View addNonScrollHeaderView() {
        return null;
    }

    @Override
    protected View addOutHeaderView() {
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.layout_librarybook_search, null);

        etSearch = inflate.findViewById(R.id.search_edit);
        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                boolean backValue = actionId == EditorInfo.IME_ACTION_SEARCH;
                if (backValue) {
                    search();
                }
                hideKeyBoard(etSearch);
                return backValue;
            }
        });
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if(etSearch.getText().length() > 0){
                    mIvTextClear.setVisibility(View.VISIBLE);
                }else {
                    mIvTextClear.setVisibility(View.INVISIBLE);
                }
                mTvSearchKeyWord.setText("\"" + etSearch.getText().toString() + "\"");
                if (etSearch.getText().toString().length() == 0) {
                    mSearchKeyWord.setVisibility(View.GONE);
                } else {
                    mSearchKeyWord.setVisibility(View.VISIBLE);
                }
            }
        });
        mSearchKeyWord = inflate.findViewById(R.id.llayout_search_keyword);
        mTvSearchKeyWord = inflate.findViewById(R.id.tv_search_keyword);
        mTvSearchKeyWord.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                search();
                hideKeyBoard(etSearch);
            }
        });
        mIvTextClear = inflate.findViewById(R.id.iv_text_clear);
        mIvTextClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                etSearch.setText("");
                hideKeyBoard(etSearch);
                search();
            }
        });
        return inflate;
    }

    private void hideKeyBoard(TextView v) {
        /*隐藏软键盘*/
        InputMethodManager imm = (InputMethodManager) v
                .getContext().getSystemService(
                        Context.INPUT_METHOD_SERVICE);
        if (imm.isActive()) {
            imm.hideSoftInputFromWindow(
                    v.getApplicationWindowToken(), 0);
        }
    }

    private void search() {
        getMyModelImpl().search(mContext, etSearch.getText().toString());
        mSelectedPositions.clear();
    }

    @Override
    protected void initBundle() {
        setTitleText("选择文库");

        boolean booleanExtra = getIntent().getBooleanExtra(Constants.CANCHOOSE, true);
        setEditable(booleanExtra, true);
    }

    @Override
    protected boolean showTitle() {
        return true;
    }

    @Override
    public boolean showRight() {
        return true;
    }

    @Override
    public String showRightText() {
        return "发送";
    }

    @Override
    public void toDoRightSomething() {
        if (getCheckedItems().size() == 0) {
            ToastUtil.show("请先选择一个");
            return;
        }

        LibraryBookBean.ResultBean.DataBean listBean = getCheckedItems().get(0);

        Intent intent = new Intent();
        intent.putExtra("url", listBean.getDocPath());
        intent.putExtra("name", listBean.getTitle());
        intent.putExtra("size", listBean.getDocSize());

        setResult(200, intent);
        finish();

    }

    @Override
    protected void doSomeBindEvent() {
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                ToggleButton toggleButton = (ToggleButton) view.findViewById(R.id.tg_edit_selector);
                toggleButton.setChecked(!toggleButton.isChecked());
            }
        });
    }

    @Override
    public int showRightImg() {
        return R.drawable.title_bar_compose;
    }

    @Override
    public MyLibraryBookModellImpl getMyModelImpl() {
        if (mListModel == null) {
            mListModel = new MyLibraryBookModellImpl();
        }
        return mListModel;
    }
}
